package giotto2D.filters.color;

import giotto2D.filters.AbstractFilter;
import giotto2D.filters.color.Desaturate;
import java.awt.image.*;
import java.awt.*;

public class SmoothThreshold extends AbstractFilter
{
	private int look[] = new int[256];

	public SmoothThreshold()
	{
		setThreshold( 128, 2);
	}

	public void setThreshold( int thresh, int slopeHalfWidth )
	{
		int sStart = thresh - slopeHalfWidth;
		int sEnd = thresh + slopeHalfWidth;
		for( int i = 0; i < 256; i++ )
		{
			if( i < sStart)
			{
				look[ i ] = 0;
			}
			else if( i > sEnd )
			{
				look[ i ] = 255;
			}
			else
			{
				int val = (int)(255.0f * ((float)( i - sStart)) / ((float)sEnd - sStart));
				look[ i ] = val;
			}
		}
	}

	public void filter( BufferedImage img )
	{
		WritableRaster imgRaster = img.getRaster();

		//--- Create pixel objects outside loop.
		int[] pixel = new int[ 4 ];
		int valueDivider = 3 * 255;
		int value;
		int i, j;

		//--- Draw loops.
		for( i = 0; i < img.getWidth(); i++ )
		{
			for( j = 0; j < img.getHeight(); j++ )
			{
				imgRaster.getPixel( i, j, pixel );
				value = (( pixel[ RED ] + pixel[ BLUE ] + pixel[ GREEN ] ) * 255 )
											/ valueDivider;
				pixel[ RED ] = look[value];
				pixel[ GREEN ] = look[value]; 
				pixel[ BLUE ] = look[value]; 

				imgRaster.setPixel(i, j, pixel );
			}
		}
	}

}//end class